package com.tju.Controller.system;


import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.tju.Model.RoleType;
import com.tju.Model.User;
import com.tju.Util.EncryptionUtil;
import com.tju.Util.ResultDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tju.Service.ResourcesService;
import com.tju.Service.UserRoleService;
import com.tju.Service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Slf4j
@Controller
public class AdminController {

    @Resource
    UserService userServiceImpl;

    @Resource
    ResourcesService resourcesServiceImpl;

    @Resource
    UserRoleService userRoleServiceImpl;

    @RequestMapping(value = "/main/admin/index", method = RequestMethod.GET)
    public String admin(HttpServletRequest request, Model model) {
   /*     HttpSession session = request.getSession();
        int loginId = (int) session.getAttribute("loginId");
        String menuTree = buildMenuTree(loginId);
        if(menuTree!=null)
        {
            model.addAttribute("isMenuCreateSuccess",true);
            model.addAttribute("menuList",menuTree);
        }else{
            model.addAttribute("isMenuCreateSuccess",false);
        }*/
        return "admin/index";
    }

    @RequestMapping(value = "/main/user/index", method = RequestMethod.GET)
    public String user(HttpServletRequest request, Model model) {
        log.info("user");
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        userDetails.getUsername();
        return "admin/indexuser";
    }

    @RequestMapping(value = "/admin/user_manage", method = RequestMethod.GET)
    public String user_manage(HttpServletRequest request, Model model) {
        log.info("用户管理");
        ResultDO<List<User>> listResultDO = userServiceImpl.selectAllUserList();
        if (listResultDO.isSuccess()) {
            model.addAttribute("queryUserResult", true);
            model.addAttribute("userList", listResultDO.getModule());
        } else {
            model.addAttribute("queryUserResult", false);
        }

        return "admin/user_manage";
    }


    @RequestMapping(value = "/system/alarm", method = RequestMethod.GET)
    public String alarm(HttpServletRequest request, Model model) {
        log.info("系统预警");
        return "admin/alarm";
    }

    @RequestMapping(value = "/admin/insertUser")
    @ResponseBody
    public String insertUser(HttpServletRequest request, @RequestBody User user, Model model) {
        user.setUserRole(0);
        return insertUserInfo(user, RoleType.ROLE_USER);
    }

    @RequestMapping(value = "/admin/insertAdminUser")
    @ResponseBody
    public String insertAdminUser(HttpServletRequest request, @RequestBody User user, Model model) {
        String roleName;
        //管理员添加用户均可用
        user.setUserFlag(1);
        if (user.getUserRole() == 0) {
            return insertUserInfo(user, RoleType.ROLE_USER);
        } else {
            return insertUserInfo(user, RoleType.ROLE_ADMIN);
        }
    }

    private String insertUserInfo(User user, RoleType roleType) {
       ResultDO<Boolean> booleanResultDO = new ResultDO<>();
        try {
            user.setUserPwd(EncryptionUtil.getHash(user.getUserPwd(), "MD5"));
            user.setDatetime(new Date());
            return JSON.toJSONString(userServiceImpl.insertNewUser(user, roleType));
        } catch (Exception e) {
            log.error("增加新用户失败，params：{}", user.toString());
            booleanResultDO.setErrorCode("增加用户失败，请重试");
        }
        return JSON.toJSONString(booleanResultDO);
    }

    @RequestMapping(value = "/admin/updateUserFlag", method = RequestMethod.POST)
    @ResponseBody
    public String updateUserFlag(HttpServletRequest request, Model model) {
        log.info("更改用户状态");
        String userId = request.getParameter("userId").trim();
        String userFlag = request.getParameter("userFlag").trim();
        Preconditions.checkArgument(StringUtils.isNotBlank(request.getParameter("userId")), "用户ID不能为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(request.getParameter("userFlag")), "userFlag不能为空");
        ResultDO<Boolean> booleanResultDO = new ResultDO<>();
        try {
            User updateUser = userServiceImpl.selectByPrimaryKey(Integer.parseInt(userId));
            if (updateUser != null) {
                updateUser.setUserFlag(Integer.parseInt(userFlag));
                booleanResultDO = userServiceImpl.updateUserInfo(updateUser);
            } else {
                booleanResultDO.setErrorCode("未找到指定ID的用户");
            }
        } catch (Exception e) {
            booleanResultDO.setErrorCode("参数有误");
        }
        return JSON.toJSONString(booleanResultDO);
    }

    /*public String buildMenuTree(int userId){
        //获取系统菜单
        ResultDO<List<MenuObject>> systemMenuList = resourcesServiceImpl.getSystemMenuList();
        //获取用户权限
        ResultDO<List<MenuObject>> accessResultDO = userRoleServiceImpl.selectMenusByUserID(userId);
        if(systemMenuList.isSuccess())
        {
            if(accessResultDO.isSuccess())
            {
                systemMenuList.getModule().addAll(accessResultDO.getModule());
            }
            MenuTree myMenuTree = new MenuTree(systemMenuList.getModule());
            return myMenuTree.buildTree();
        }else{
            return null;
        }
    }*/
}
